import cgi
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from entities import *


def Add(tenNguoiDung,UngDung,VaiTroID):
    vaitro = Entities.VaiTro.get_by_id(VaiTroID)    
    nguoidung = db.GqlQuery("SELECT * FROM NguoiDung WHERE TenNguoiDung = :1 AND UngDung = :2",
                              tenNguoiDung, UngDung) 
    #tennguoidung = users.User(TenNguoiDung)
    if nguoidung.count() == 0:
        try:
        #tennguoidung = TenNguoiDung
            nguoidung= Entities.NguoiDung(TenNguoiDung=tenNguoiDung,VaiTro=vaitro)
            nguoidung.UngDung = UngDung
            nguoidung.put()
            return "Complete"
        except:
            return "Error"
    else:
        return "Duplicate"
def Get(TenNguoiDung):
    nguoidungs = Entities.NguoiDung.gql('WHERE TenNguoiDung = :1',TenNguoiDung)
    if nguoidungs.count() != 0:
        for nguoidung in nguoidungs:
            VaiTro = nguoidung.VaiTro
    else:
        VaiTro = None
    return VaiTro

def GetKey(TenNguoiDung):
    nguoidungs =Entities. NguoiDung.gql('WHERE TenNguoiDung = :1',TenNguoiDung)
    if nguoidungs.count() != 0:
        for nguoidung in nguoidungs:
            NguoiDungID = nguoidung.key()
    else:
        NguoiDungID = None
    return NguoiDungID

def GetTenVaiTro(user):
    vaitro = Get(user)
    TenVaiTro = ""
    if vaitro:
        vaitro_ID = vaitro.key().id()
        VaiTros = VaiTroEntities.Get(vaitro_ID)
        for vaitro in VaiTros:
            TenVaiTro = vaitro['TenVaiTro']
    return TenVaiTro      